from django.shortcuts import render
from django.http import HttpResponse


# Create your views here.
def index(request):
    return render(request, "usercenter.html", {})


def escape(requet):
    return render(requet, "escapetest.html", {"ec": "<h1>转义字符串</h1>"})


def verifycode(request):
    from PIL import Image, ImageDraw, ImageFont
    import random
    # 创建一个画布(Image)
    bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
    width = 100
    height = 25
    im = Image.new(mode='RGB', size=(width, height), color=bgcolor)

    # 创建一个画笔
    draw = ImageDraw.Draw(im)

    # 设置噪点

    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy=xy, fill=fill)

    # 用笔画出文本

    str1 = 'ABCDEFG1234HIJKMLN456OPQRST789UVWXYZ0'

    rand_str = ""
    for i in range(0, 4):
        rand_str = rand_str + str1[random.randrange(0, len(str1))]

    # 设置文本字体
    font = ImageFont.truetype('simsun.ttc', 23, index=1)

    # 设置字体颜色
    font_color = (255, random.randrange(0, 255), random.randrange(0, 255))

    draw.text(xy=(5, 2), text=rand_str[0], fill=font_color, font=font)
    draw.text(xy=(25, 2), text=rand_str[1], fill=font_color, font=font)
    draw.text(xy=(50, 2), text=rand_str[2], fill=font_color, font=font)
    draw.text(xy=(75, 2), text=rand_str[3], fill=font_color, font=font)
    del draw

    import io
    # python3中使用io.BytesIO()将图片保存到内存中
    buf = io.BytesIO()
    im.save(buf, 'png')
    request.session['verify_code'] = rand_str

    # 将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(content=buf.getvalue(), content_type='image/png')
